"""生成token值,单点登录,60s"""
import datetime
import time
from bms.settings import SECRET_KEY
from itsdangerous import TimedJSONWebSignatureSerializer as TJSSerializer

class CreateToken(object):
    def __init__(self,user,password):
        self.user = user
        self.password = password
        self.secret_key = SECRET_KEY

    def create_token(self,id):
        # 生成token
        serializer = TJSSerializer(self.secret_key,60)
        # 添加数据 user,返回一个byte类型
        context = {
            "id":id,
            "user":self.user,
            "password":self.password,
            "time":time.strftime('%Y%m%d:%H%M%S')
        }
        token_byte = serializer.dumps(context)
        token = token_byte.decode()
        return token

class CheckToken(object):
    def __init__(self):
        self.secret_key = SECRET_KEY

    def check_token(self,token):
        # 校验token
        serializer = TJSSerializer(self.secret_key,60)
        # 解析token值,有返回值(字典)
        try:
            data = serializer.loads(token)
        except Exception as e:
            return None
        id = data['id']
        username = data['user']
        password = data['password']
        data = {
            "id":id,
            "username":username,
            "password":password
        }
        return data